import json

from requests import post
import uuid
import sql
from procedureLog import ExecutionLog
from websocket_information import WebSocketController


def get_param_names(ws, task_uuid, message):
    device = sql.get_device(message)
    addressee = str(device[3])
    addressee_name = device[1]
    task_id = str(uuid.uuid1())
    addressee_url = addressee + '/downEquipmentFunction'

    mes_info = {'sender': 'websocket', 'addresseeId': message, 'taskId': task_id,
                'command': {'target': 'GetParamNames'}}
    mes_info = json.dumps(mes_info)

    article_info = {}
    data = json.loads(json.dumps(article_info))
    data['uuid'] = task_uuid
    data['message'] = None
    try:
        r = post(url=addressee_url, data=mes_info)
        if r.status_code == 200:
            data['message'] = r.json()
        # 写入日志
        ExecutionLog.executionLog(taskId=task_id, senderName='websocket', addresseeId=message,
                                  addresseeName=addressee_name,
                                  interface=addressee_url, statusCode=r.status_code)
    except Exception:
        # 写入日志
        ExecutionLog.executionLog(taskId=task_id, senderName='websocket', addresseeId=message,
                                  addresseeName=addressee_name,
                                  interface=addressee_url, statusCode=400)

    article = json.dumps(data, ensure_ascii=False)
    WebSocketController.on_send(ws, article)


def modify_params(ws, task_uuid, message):
    device_id = message['device_id']
    device = sql.get_device(device_id)

    message['target'] = 'ModifyParams'
    del message['device_id']

    addressee = str(device[3])
    addressee_name = device[1]
    task_id = str(uuid.uuid1())
    addressee_url = addressee + '/downEquipmentFunction'
    article = {'sender': 'websocket', 'addresseeId': device_id, 'taskId': task_id,
               'command': message}
    article = json.dumps(article)
    r = post(url=addressee_url, data=article)
    print(r.json())
    try:
        # 写入日志
        ExecutionLog.executionLog(taskId=task_id, senderName='websocket', addresseeId=device_id,
                                  addresseeName=addressee_name,
                                  interface=addressee_url, statusCode=r.status_code)
    except Exception as e:
        print(e)
    article_info = {}
    data = json.loads(json.dumps(article_info))
    data['uuid'] = task_uuid

    data['message'] = r.json()
    article = json.dumps(data, ensure_ascii=False)
    WebSocketController.on_send(ws, article)
